﻿using UnityEngine;
using System.Collections;

public class LaserArcScan : MonoBehaviour {

    public float arcSweepRate = 3600;        // Rate of scan line rotation within the scanning arc in degrees/s

    private Transform directionIndicator;
    private Transform laser;
    private Transform scanLine;
    private ScanLineManager scanLineManager = null;

    public float currentArcTheta = 0;     // Used for sweeping the arc, see Update
    private float lastArcTheta = 0;

    public bool doSweep = true;
    private bool negativeSide = false;

    // Use this for initialization
	void Start () {

        laser = transform.FindChild("Laser");

        directionIndicator = laser.FindChild("DirectionIndicator");

        scanLine = transform.parent;
        scanLineManager = scanLine.GetComponent<ScanLineManager>();

        if (!doSweep)
        {
            if (currentArcTheta < 0) negativeSide = true;
            lastArcTheta = currentArcTheta;
        }
    }
	
	// Update is called once per frame
	void Update () {

        if (doSweep)
        {
            currentArcTheta += arcSweepRate * Time.deltaTime;
            currentArcTheta = currentArcTheta % (scanLineManager.currentArcSize * 2);

            float trueTheta = currentArcTheta;
            if (trueTheta > scanLineManager.currentArcSize)
            {
                trueTheta = 2 * scanLineManager.currentArcSize - trueTheta;
            }

            trueTheta -= scanLineManager.currentArcSize / 2;

            float currentChange = trueTheta - lastArcTheta;

            transform.Rotate(transform.forward, currentChange);

            lastArcTheta = trueTheta;
        }
        else
        {
            currentArcTheta = negativeSide ? scanLineManager.currentArcSize / -2 : scanLineManager.currentArcSize / 2;
            transform.localRotation = Quaternion.identity;
            transform.Rotate(transform.forward, currentArcTheta);
        }

        float currentScanDistance = scanLineManager.scanDistance;
        RaycastHit hitInfo;
        if (Physics.Raycast(transform.position, directionIndicator.position - transform.position, out hitInfo, scanLineManager.scanDistance))
        {
            currentScanDistance = hitInfo.distance;
        }

        // Keep the length updated
        transform.localScale = new Vector3(currentScanDistance, 1, 1);
    
    }
}
